//
//  selectTableViewController.m
//  SouthChina
//
//  Created by zorro on 15/7/1.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "selectTableViewController.h"
#import "AddressBookTableViewCell.h"
#import "CreateGroupViewController.h"
#import "selectMemberTableViewCell.h"
#import "selectMemberViewController.h"
#import "GroupInfoViewController.h"
@interface selectTableViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate ,UnitViewDelegate>
{

    NSArray * keySortList;
    long childSize;
    NSMutableDictionary *keyCountMap;
    UISearchDisplayController *searchDisplayController;

}
@end

@implementation selectTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addTitleBarWithBackBtn:_curOrgContact.mNAME needReturn:TRUE];
    
    UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"selectTableViewBody" owner:self options:nil] objectAtIndex:0];
    
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:viewBody];
    

    _searchMember.showsCancelButton=NO;
    _searchMember.barStyle=UIBarStyleDefault;
    _searchMember.placeholder = @"搜索";
    _searchMember.delegate = self;
  
    
    _tabMember.delegate = self;
    _tabMember.dataSource = self;
    _tabMember.bounces=NO;
    
    [self resortContactList:@""];
    [_tabMember reloadData];
    
    if([_CreateType isEqualToString:@"SHOW_USER"])
        return;
    
    //需要重新设置
    _selectMemberList.isDoneButton = YES;
    _selectMemberList = [_selectMemberList initWithFrame:_selectMemberList.frame];
   _selectMemberList.delegate = self;

    for( Contact * contact in _selectedContact)
    {
        [_selectMemberList addNewUnit:contact];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    [self resortContactList:searchText];
    [_tabMember reloadData];
    
}
// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self resortContactList:@""];
    [_tabMember reloadData];
}

-(void)resortContactList:(NSString*)key{
    NSArray * orgContactList = nil;
    //_curOrgContact.mID如果展示的最近联系人，
    if([_curOrgContact.mID isEqualToString: RECENTLYCONTACT])
    {
        orgContactList = [ContactDao queryRecentlyCcontact:key];
    }
    else
    {
        orgContactList = [ContactDao searcherNodeContact:_curOrgContact.mID key:key];
    }
    
    orgContactList= [orgContactList sortedArrayUsingComparator:^NSComparisonResult(Contact *p1, Contact *p2){
        
        return [p1.mQP compare:p2.mQP];
        
    }];
    
    childSize = orgContactList.count;
    keyCountMap = [[NSMutableDictionary alloc] init];
    
    bool isshow = [@"OFF" isEqualToString:[DE getGlobalVar:IS_SHOW_UNACTIVE_USER]];
    for (int i=0; i<orgContactList.count; i++) {
        
        Contact*contact =[orgContactList objectAtIndex:i];
        
        if (isshow)
        {
            if ([contact.mHEAD_IMG hasSuffix:@"defaultheadimg.png"]) {
                continue;
            }
        }
        NSString *key = [contact.mQP.length>=1?contact.mQP:@"#" substringToIndex:1];
        if ([keyCountMap objectForKey:key]) {
            NSMutableArray *array = [keyCountMap objectForKey:key];
            [array addObject:contact];
            [keyCountMap setObject:array forKey:key];
        }else{
            NSMutableArray *array = [[NSMutableArray alloc] init] ;
            [array addObject:contact];
            [keyCountMap setObject:array forKey:key];
        }
        
    }
    
    keySortList =[keyCountMap allKeys];
    keySortList = [keySortList sortedArrayUsingComparator:^NSComparisonResult(NSString *p1, NSString *p2){
        return [p1 compare:p2];
    }];    
}


//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return keySortList.count;
}
//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}


//右边显示的内容字母
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return keySortList;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [keySortList objectAtIndex:section] ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = [keySortList objectAtIndex:section];
    NSArray *aray = [keyCountMap objectForKey:key];
    return aray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"selectMemberTableViewCell";
    selectMemberTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    }

    
    NSString *key = [keySortList objectAtIndex:indexPath.section];
    NSArray *aray = [keyCountMap objectForKey:key];
    Contact *contact =[aray objectAtIndex:indexPath.row];
    
    [cell setContactSelected:[self containsContact:_selectedContact contact:contact]];
    [cell setSelectMemberTableViewCell:contact];
    
    return cell;
}

- (BOOL)containsContact:(NSMutableSet*) set contact:(Contact *)contact
{
    for (Contact * i   in  set)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            return YES;
        }
    }
    return NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{    
    NSString *key = [keySortList objectAtIndex:indexPath.section];
    NSArray *aray = [keyCountMap objectForKey:key];
    Contact *contact =[aray objectAtIndex:indexPath.row];
    
    BOOL isFind = NO;
    for (Contact * i   in  _selectedContact)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            [_selectedContact removeObject:i];
            [_selectMemberList removeUnit:contact];
            isFind = YES;
            break;
        }
    }
    
    if (!isFind) {
        [_selectedContact addObject:contact];
        [_selectMemberList addNewUnit:contact];
    }
    
    
    NSArray *indexArray=[NSArray arrayWithObject:indexPath];
    [_tabMember reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];

}


- (void) extendCellTouched:(UnitCell *)unitCell
{
    //点击选择好的成员后，需要清理数据
    Contact *contact =unitCell.contact;
    
    for (Contact * i   in  _selectedContact)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            [_selectedContact removeObject:i];
            [_tabMember reloadData];
            break;
        }
    }
}

- (void) unitDoneTouched:(id)sender
{
    NSLog(@"点击完成按钮");
    if([_CreateType isEqualToString:CREATETYPE_CREATEGROUP])
    {
         NSLog(@"点击创建群完成按钮");
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[CreateGroupViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }
    }
    else if ([_CreateType isEqualToString:CREATETYPE_ADDGROUP])
    {
        NSLog(@"点击加群成员按钮");
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[GroupInfoViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }

    }
    else if([_CreateType isEqualToString:CREATETYPE_CREATECHAT])
    {
         NSLog(@"点击创建群讨论组按钮");
        //创建讨论组
        if(_selectedContact.count >200 || _selectedContact.count <2)
        {
            [self showAlerHUD:@"添加的成员人数不能小于2人和大于200人"];
            return;
        }
        
        /*"groupType":"1", --群组类型1 普通群 2 行政群 3 讨论组
         "userIds":"9004,9005,9006",--添加的用户列表，用逗号隔开 选填
         "groupName":"信网中心群",--群名称 选填
         "groupTags":"72,73,81",--群标签，多个值用逗号隔开 选填
         "toMountGroupId":"10000736",--挂靠的群组Id选填*/
        
        NSEnumerator *enumerator = [_selectedContact objectEnumerator];
        NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
        [ids insertString:[NSString stringWithFormat:@"%@,",DE.userId] atIndex:0];
        for (Contact *cid in enumerator) {
            [ids insertString:[NSString stringWithFormat:@"%@,",cid.mID] atIndex:0];
        }
      
        NSDictionary *dict  = @{@"groupType":@"3",
                                @"userIds":ids,
                                @"groupName":@"",
                                @"groupTags":@"",
                                @"toMountGroupId":@""};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"createGrp" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (success) {
                NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                
                [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                    
                    if(success){
                        @try {
                            [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                            [view show];
                        }
                        @catch (NSException *exception) {
                            [self showAlerHUD:@"创建讨论组失败！"];
                        }
                        
                    }else{
                        [self showAlerHUD:@"创建讨论组失败！"];
                        
                    }
                    
                }];
                
            }else{
                
                UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
                [view show];
            }

        }];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"创建讨论组返回=========");
    if (buttonIndex==0) {
        kAppDelegate.needRefrsh=YES;
         [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:NO];
    }
}

//回退
-(void)btnBack
{
    kAppDelegate.needRefrsh = YES;
    [super btnBack];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
